<?php
abstract class NoBusinessBase_AbstractHelper_ValueReplace extends Zend_Controller_Action_Helper_Abstract
{
   protected $_replace = null;
   protected $_search = null;
   protected static $sHttpHost = null;
   protected static $sRequestUri = null;

   public function __construct($additiveArray = null)
   {
      if(!isset($this->_search))
      {
         $this->_search  = array(
            '{Domain}',
            '{RequestUri}',
            '%%CURRENT_USER%%',
            '%%CURRENT_GMT%%'
         );
      }

      if(self::$sHttpHost === null && self::$sRequestUri === null)
      {
         $pRequest = $this->getRequest();
         if($pRequest)
         {
            self::$sHttpHost = $pRequest->getHttpHost();
            self::$sRequestUri = $pRequest->getRequestUri();
         }
      }

      if(!isset($this->_replace))
      {
         $this->_replace = array(
            self::$sHttpHost ? self::$sHttpHost : '',
            self::$sRequestUri ? self::$sRequestUri : '',
            $this->getUser(),
            gmdate('Y-m-d H:i:s')
         );
      }
      
      if($additiveArray)
      {
         foreach($additiveArray as $key => $value)
         {
            $this->_search[] = $key;
            $this->_replace[] = $value;
         }
      }
   }

   abstract protected function getUser();

   public function direct()
   {
      return $this;
   }

   public function replaceValue($value)
   {
      switch($value)
      {
         case '%%RANDOM_STRING_4%%': return NoBusinessBase_Utility_String::genRandomString(4);
         case '%%RANDOM_STRING_8%%': return NoBusinessBase_Utility_String::genRandomString(8);
         case '%%RANDOM_STRING_16%%': return NoBusinessBase_Utility_String::genRandomString(16);
         case '%%RANDOM_STRING_32%%': return NoBusinessBase_Utility_String::genRandomString(32);
         case '%%RANDOM_HASH%%': return md5(NoBusinessBase_Utility_String::genRandomString(56));
         case '%%RANDOM_PERCENT%%': return mt_rand() / mt_getrandmax();
      }
      return $value === null ? $value : str_replace($this->_search, $this->_replace, $value);
   }
   public function replaceValuesInArray(&$arr)
   {
      if(!is_array($arr))
         return;

      foreach($arr as $name => &$value)
      {
         if(is_array($value))
            $this->replaceValuesInArray($value);
         else
            $value = $this->replaceValue($value);
      }
   }
}

